<?php

namespace app\admin\controller\api;

use app\common\model;

/**
 * 教室
 * @internal
 */
class Classroom extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 教室列表
     *
     * @param school_id int 学校id
     * @param classroom_ids string 教室ids
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $school_id = $this->request->request('school_id');
        $classroom_ids = $this->request->request('classroom_ids');
        $gardens = model\Garden::where('school_id', $school_id)->select();
        $buildings = model\Building::with('classrooms')->whereIn('garden_id', array_column($gardens, 'id'))->select();

        if ($classroom_ids && !is_array($classroom_ids)) {
            $classroom_ids = explode(',', $classroom_ids);
        }
        $data = [];
        foreach ($buildings as $key => $building) {
            $children = [];
            $all_check = "1"; //假设全部选中
            foreach ($building['classrooms'] as $k => $classroom) {
                $checkArr = "0";
                if ($classroom_ids && in_array($classroom['id'], $classroom_ids)) {
                    $checkArr = "1";
                } else {
                    $all_check = "0";
                }
                $children[] = [
                    "id" => $building['id'] . $classroom['id'],
                    "basicData" => $classroom['id'],
                    "title" => $classroom['name'],
                    "last" => true,
                    "parentId" => $building['id'],
                    "checkArr" => $checkArr,
                ];
            }

            $data[] = [
                "id" => $building['id'],
                "title" => $building['name'],
                "last" => false,
                "parentId" => "0",
                "checkArr" => $all_check,
                "children" => $children,
            ];
        }

        $this->success('', $data);
    }

}